package com.maori.languageapp.discover.word;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONObject;
import com.maori.languageapp.R;
import com.maori.languageapp.adapter.Languageapp_Curate_AudioView_Activity;
import com.maori.languageapp.adapter.Languageapp_Curate_VideoView_Activity;
import com.maori.languageapp.consts.ImageLoader;
import com.maori.languageapp.discover.word.Maori_Discover_Word_Details;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.AsyncTask;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

public class Maori_Discover_AudioList_Word_Adapter extends BaseAdapter {
	protected static final String TAG = null;
	// Declare Variables
	Context context;
	LayoutInflater inflater;
	ArrayList<HashMap<String, String>> data;
	// Button videoview_example;
	ImageLoader imageLoader;
	String UserLikedAudio, AudioParentNID, AudioParentUID, AudioNID, result,
			AudioMediaID, TotalsSetDefaultAudio, SynMediaType, SynUserID,
			SynNodeId, SynParentNodeId;
	private MediaPlayer mediaPlayer;
	int timeoutConnection = 5000;
	HttpParams httpParameters = new BasicHttpParams();
	InputStream is = null;
	StringBuilder sb = null;
	private LayoutInflater mInflater;
	HashMap<String, String> resultp = new HashMap<String, String>();
	String MediaUID, NodeMediaType;

	private double startTime = 0;
	private double finalTime = 0;
	private Handler myHandler = new Handler();;
	private int forwardTime = 1000;
	private int backwardTime = 1000;
	public static int oneTimeOnly = 0;

	SeekBar seekbar;
	Button btn_pause_active, btn_play, btn_pause, btn_play_active;

	public Maori_Discover_AudioList_Word_Adapter(Context context,
			ArrayList<HashMap<String, String>> arraylist) {
		this.context = context;
		data = arraylist;
		imageLoader = new ImageLoader(context);
		mInflater = LayoutInflater.from(context);
	}

	@Override
	public int getCount() {
		return data.size();
	}

	@Override
	public Object getItem(int position) {
		return data.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	public View getView(final int position, View convertView, ViewGroup parent) {
		// Declare Variables
		final ViewHolder holder;
		if (convertView == null) {
			convertView = mInflater.inflate(
					R.layout.languageapp_discover_audio, null);
			holder = new ViewHolder();
			holder.first_name = (TextView) convertView
					.findViewById(R.id.firstname);
			holder.user_role = (TextView) convertView
					.findViewById(R.id.lastname);
			holder.display_dialect = (Button) convertView
					.findViewById(R.id.display_dialect);
			holder.display_location = (Button) convertView
					.findViewById(R.id.display_location);
			holder.userimage = (ImageView) convertView
					.findViewById(R.id.userimggriditem);
			holder.setLikeAction = (Button) convertView
					.findViewById(R.id.setLikeAction);
			holder.setDefAction = (Button) convertView
					.findViewById(R.id.setDefAction);
			holder.urlreader = (Button) convertView
					.findViewById(R.id.urlreader);

			holder.seekbar = (SeekBar) convertView.findViewById(R.id.seek_bar);

			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}

		resultp = data.get(position);

		imageLoader.DisplayImage(
				resultp.get(Maori_Discover_Word_Details.getIMAGEMID()),
				holder.userimage);
		holder.first_name.setText(resultp.get(Maori_Discover_Word_Details
				.getIMAGEfirst_name())
				+ " "
				+ resultp.get(Maori_Discover_Word_Details.getIMAGElast_name()));
		holder.user_role.setText(resultp.get(Maori_Discover_Word_Details
				.getSYNtribe()));
		holder.display_dialect.setText(resultp.get(Maori_Discover_Word_Details
				.getAudioSyndialact()));
		holder.display_location.setText(resultp.get(Maori_Discover_Word_Details
				.getSYNcurrent_location()));
		holder.setLikeAction
				.setText("Like ("
						+ resultp.get(Maori_Discover_Word_Details
								.getIMAGETotalsLikes()) + ")");

		MediaUID = resultp.get(Maori_Discover_Word_Details.getMediaUID());
		NodeMediaType = resultp.get(Maori_Discover_Word_Details
				.getNodeMediaType());

		UserLikedAudio = resultp.get(Maori_Discover_Word_Details
				.getUserLikedAudio());
		AudioParentNID = resultp.get(Maori_Discover_Word_Details
				.getAudioParentNID());
		AudioParentUID = resultp.get(Maori_Discover_Word_Details
				.getAudioParentUID());
		TotalsSetDefaultAudio = resultp.get(Maori_Discover_Word_Details
				.getTotalsSetDefaultAudio());
		/********** if user liked Like Button Set to Active ******************/

		if (TotalsSetDefaultAudio.equals("0")) {
			holder.setDefAction.setCompoundDrawablesWithIntrinsicBounds(
					R.drawable.ic_default_inactive, 0, 0, 0);
		} else {
			holder.setDefAction.setCompoundDrawablesWithIntrinsicBounds(
					R.drawable.ic_default_active, 0, 0, 0);
		}

		Log.v("UserLikedAudio ", ":" + UserLikedAudio);
		if (UserLikedAudio.equals("0")) {
			holder.setLikeAction.setCompoundDrawablesWithIntrinsicBounds(
					R.drawable.ic_like_inactive_h, 0, 0, 0);
		} else {
			holder.setLikeAction.setCompoundDrawablesWithIntrinsicBounds(
					R.drawable.ic_like_h, 0, 0, 0);
		}

		holder.setDefAction.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				TotalsSetDefaultAudio = resultp.get(Maori_Discover_Word_Details
						.getTotalsSetDefaultAudio());

				if (TotalsSetDefaultAudio.equals("0")) {
					holder.setDefAction
							.setCompoundDrawablesWithIntrinsicBounds(
									R.drawable.ic_default_active, 0, 0, 0);
				} else {
					holder.setDefAction
							.setCompoundDrawablesWithIntrinsicBounds(
									R.drawable.ic_default_inactive, 0, 0, 0);
				}
				resultp = data.get(position);
				SynUserID = resultp.get(Maori_Discover_Word_Details
						.getAudioParentUID());
				SynNodeId = resultp.get(Maori_Discover_Word_Details
						.getIMAGENM_ID());
				SynParentNodeId = resultp.get(Maori_Discover_Word_Details
						.getAudioParentNID());
				SynMediaType = "2";

				new UploadSetDefaultDetails().execute();
			}
		});

		holder.urlreader.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// Get the position from the results
				final Dialog dialog = new Dialog(context);
				dialog.setContentView(R.layout.language_app_audio_dialog);
				dialog.setTitle("Play Audio");

				seekbar = (SeekBar) dialog.findViewById(R.id.seekbaraudio);
				btn_pause_active = (Button) dialog.findViewById(R.id.btn_pause_active);
				btn_play = (Button) dialog.findViewById(R.id.btn_play);
				btn_pause = (Button) dialog.findViewById(R.id.btn_pause);
				btn_play_active = (Button) dialog.findViewById(R.id.btn_play_active);

				btn_play.setOnClickListener(new OnClickListener() {

					public void onClick(View v) {
						playAudio(v);
					}
				});

				btn_pause.setOnClickListener(new OnClickListener() {

					public void onClick(View v) {
						pauseAudio(v);
					}
				});

				HashMap<String, String> resultp = new HashMap<String, String>();
				resultp = data.get(position);
				String AudioUrlSource = resultp.get(Maori_Discover_Word_Details
						.getIMAGEM_Source());

				mediaPlayer = new MediaPlayer();
				mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
				try {
					mediaPlayer.setDataSource(AudioUrlSource);
					mediaPlayer.prepare();
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (SecurityException e) {
					e.printStackTrace();
				} catch (IllegalStateException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}

				//mediaPlayer.start();
				seekbar.setClickable(false);
				btn_pause.setEnabled(false);
				dialog.show();
				/*
				 * finalTime = mediaPlayer.getDuration(); startTime =
				 * mediaPlayer.getCurrentPosition();
				 * 
				 * if (oneTimeOnly == 0) { holder.seekbar.setMax((int)
				 * finalTime); oneTimeOnly = 1; }
				 * holder.seekbar.setProgress((int)startTime);
				 * myHandler.postDelayed(new
				 * UpdateSongTime(holder.seekbar),100);
				 */

			}
		});

		holder.setLikeAction.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				HashMap<String, String> resultp = new HashMap<String, String>();
				resultp = data.get(position);

				UserLikedAudio = resultp.get(Maori_Discover_Word_Details
						.getUserLikedAudio());
				AudioMediaID = resultp.get(Maori_Discover_Word_Details
						.getIMAGENM_ID());
				AudioNID = resultp.get(Maori_Discover_Word_Details
						.getIMAGENID());
				AudioParentNID = resultp.get(Maori_Discover_Word_Details
						.getAudioParentNID());
				AudioParentUID = resultp.get(Maori_Discover_Word_Details
						.getAudioParentUID());

				String TotalLikesAudio = resultp
						.get(Maori_Discover_Word_Details.getIMAGETotalsLikes());
				int TotalLikesVal = Integer.parseInt(TotalLikesAudio);

				if (UserLikedAudio.equals("0")) {
					UserLikedAudio = "1";
					holder.setLikeAction
							.setCompoundDrawablesWithIntrinsicBounds(
									R.drawable.ic_like_h, 0, 0, 0);
					TotalLikesVal = TotalLikesVal + 1;
					holder.setLikeAction.setText("Like (" + "" + TotalLikesVal
							+ ")");

					// Update Values Of the Hash Map Position
					resultp.put("IMAGETotalsLikes", "" + TotalLikesVal);
					resultp.put("UserLikedAudio", UserLikedAudio);

				} else {
					UserLikedAudio = "0";
					holder.setLikeAction
							.setCompoundDrawablesWithIntrinsicBounds(
									R.drawable.ic_like_inactive_h, 0, 0, 0);
					TotalLikesVal = TotalLikesVal - 1;
					holder.setLikeAction.setText("Like (" + "" + TotalLikesVal
							+ ")");

					// Update Values Of the Hash Map Position
					resultp.put("IMAGETotalsLikes", "" + TotalLikesVal);
					resultp.put("UserLikedAudio", UserLikedAudio);
				}

				new UploadLikeStateDetails().execute();
			}
		});
		return convertView;
	}

	static class ViewHolder {
		Button setDefAction;
		Button setLikeAction;
		Button urlreader;
		TextView first_name;
		TextView last_name;
		TextView user_role;
		ImageView userimage;
		Button display_location;
		Button display_dialect;
		SeekBar seekbar;
		ImageView flag;

	}

	private class UploadSetDefaultDetails extends AsyncTask<Void, Void, Void> {
		private final String TAG = null;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			try {
				HttpPost httppost = null;
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				JSONObject json = new JSONObject();
				httppost = new HttpPost(
						"http://langapp.mirzabros.com/maoriapi/saveUsersSetDefaults.php");
				// Selected Type ID / content_type_id
				json.put("record1", SynUserID);
				// Selected UID / added_by
				json.put("record2", SynNodeId);

				json.put("record3", SynMediaType);

				json.put("record4", SynParentNodeId);
				JSONArray postjson = new JSONArray();
				postjson.put(json);
				Log.v("TAG", "POST SET DEF : " + postjson);
				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				if (is != null) {

					BufferedReader reader = new BufferedReader(
							new InputStreamReader(is, "iso-8859-1"), 8);
					sb = new StringBuilder();
					sb.append(reader.readLine() + "\n");
					String line = "0";

					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					is.close();
					result = sb.toString();
					Log.v("TAG", "Print Res***:" + result);
					if (result != null) {

					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void args) {
			Intent intent = new Intent(context,
					Maori_Discover_Word_Details.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			intent.putExtra("nid", SynParentNodeId);
			context.startActivity(intent);
			((Maori_Discover_Word_Details) context).finish();
		}
	}

	private class UploadLikeStateDetails extends AsyncTask<Void, Void, Void> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			try {
				HttpPost httppost = null;
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				JSONObject json = new JSONObject();
				httppost = new HttpPost(
						"http://langapp.mirzabros.com/maoriapi/saveNodeMediaLike.php");
				// Selected Type ID / content_type_id
				Log.e("SYN", "NID : " + AudioNID);
				Log.e("SYN", "UID : " + AudioParentUID);
				json.put("record1", AudioNID);
				json.put("record2", AudioParentUID);
				json.put("record3", "2");
				json.put("record4", AudioMediaID);

				JSONArray postjson = new JSONArray();
				postjson.put(json);

				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				if (is != null) {

					BufferedReader reader = new BufferedReader(
							new InputStreamReader(is, "iso-8859-1"), 8);
					sb = new StringBuilder();
					sb.append(reader.readLine() + "\n");
					String line = "0";

					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					is.close();
					result = sb.toString();
					if (result != null) {

					}
				}
			} catch (Exception e) {
				e.printStackTrace();

			}
			return null;
		}

		@Override
		protected void onPostExecute(Void args) {
			Log.v("LIKE Prent NID ", ":" + AudioParentNID);
			Log.v("LIKE AudioNID ", ":" + AudioNID);
			/*
			 * Intent intent = new Intent(context,
			 * Maori_Discover_Word_Details.class); intent.putExtra("nid",
			 * AudioParentNID); context.startActivity(intent);
			 */
		}
	}
	
	
	//*************Audio Dialog Controller*************
	class UpdateSongTime implements Runnable {

		private SeekBar seek;

		public UpdateSongTime() {
			// TODO Auto-generated constructor stub
		}

		public UpdateSongTime(SeekBar seekbar) {
			// TODO Auto-generated constructor stub
			this.seek = seekbar;
		}

		@Override
		public void run() {
			startTime = mediaPlayer.getCurrentPosition();
			seek.setProgress((int) startTime);
			myHandler.postDelayed(this, 100);
		}

	}
	public void playAudio(View view) {
		mediaPlayer.start();
		finalTime = mediaPlayer.getDuration();
		startTime = mediaPlayer.getCurrentPosition();
		if (oneTimeOnly == 0) {
			seekbar.setMax((int) finalTime);
			oneTimeOnly = 1;
		}

		btn_pause_active.setText(String.format(
				"%d min, %d sec",
				TimeUnit.MILLISECONDS.toMinutes((long) finalTime),
				TimeUnit.MILLISECONDS.toSeconds((long) finalTime)
						- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS
								.toMinutes((long) finalTime))));
		btn_play_active.setText(String.format(
				"%d min, %d sec",
				TimeUnit.MILLISECONDS.toMinutes((long) startTime),
				TimeUnit.MILLISECONDS.toSeconds((long) startTime)
						- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS
								.toMinutes((long) startTime))));
		seekbar.setProgress((int) startTime);
		myHandler.postDelayed(UpdateSongTime, 100);
		btn_pause.setEnabled(true);
		btn_play.setEnabled(false);
		
		mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
			public void onCompletion(MediaPlayer mp) {
				//mediaPlayer.pause();
				mediaPlayer.reset();
				Log.e("########", "Audio Play Completed...");
			}
		});

	}
	
	private Runnable UpdateSongTime = new Runnable() {
		public void run() {
			startTime = mediaPlayer.getCurrentPosition();
			btn_play_active.setText(String.format(
					"%d min, %d sec",
					TimeUnit.MILLISECONDS.toMinutes((long) startTime),
					TimeUnit.MILLISECONDS.toSeconds((long) startTime)
							- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS
									.toMinutes((long) startTime))));
			seekbar.setProgress((int) startTime);
			myHandler.postDelayed(this, 100);
		}
	};
	public void pauseAudio(View view) {
		mediaPlayer.pause();
		btn_pause.setEnabled(false);
		btn_play.setEnabled(true);
	}
}